package com.uzai.console.service.module.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.uzai.common.enums.MerConfigKeyEnum;
import com.uzai.common.enums.MerConfigTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.module.merchant.DeviceTypeQuery;
import com.uzai.console.dto.module.merchant.MerchantSetDeviceTypeDto;
import com.uzai.console.entity.DeviceType;
import com.uzai.console.entity.MerBaseConfig;
import com.uzai.console.entity.Merchant;
import com.uzai.console.mapper.DeviceTypeMapper;
import com.uzai.console.mapper.MerBaseConfigMapper;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.mapper.SysConfigMapper;
import com.uzai.console.service.module.MerBaseConfigService;
import com.uzai.console.vo.module.merchant.MerchantDeviceTypeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/***
 * 运营商基本配置
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class MerBaseConfigServiceImpl implements MerBaseConfigService{

    @Autowired
    private DeviceTypeMapper deviceTypeMapper;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;

    /**
     * 查询运营商设备配置列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public ArrayList<MerchantDeviceTypeVo> findMerDeviceTypeList(Long merId){

        Merchant merchant = merchantMapper.selectById(merId);


        //返回对象列表
        ArrayList<MerchantDeviceTypeVo> merchantDeviceTypeVos =  new ArrayList<MerchantDeviceTypeVo>();

        //查询当前有效的设备类型
        DeviceTypeQuery deviceTypeQuery = new DeviceTypeQuery();
        deviceTypeQuery.setStatus(1); //1-有效；0-禁用
        ArrayList<DeviceType> deviceTypeVos =  deviceTypeMapper.findByList(deviceTypeQuery);
        //循环遍历设备类型，如果该运营商启用了该设备类型，就设置status=1,否则status=0
        if(deviceTypeVos != null && deviceTypeVos.size() > 0){
            //查询当前运营商的设备类型配置
            MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.DEVICE_SWITCH.getValue());
            for (DeviceType deviceType : deviceTypeVos){
                if(merBaseConfig != null){
                    JSONArray valArray = JSONObject.parseArray(Tools.getStr(merBaseConfig.getVal()));
                    //是否包含该设备KEY，包含了则设置为1，不包含为0
                    if(valArray.contains(deviceType.getKey())){
                        deviceType.setStatus(1);
                    }else{
                        deviceType.setStatus(0);
                    }
                }else{
                    deviceType.setStatus(0);
                }
                MerchantDeviceTypeVo merchantDeviceTypeVo = new MerchantDeviceTypeVo();
                BeanUtils.copyProperties(deviceType, merchantDeviceTypeVo);
                merchantDeviceTypeVos.add(merchantDeviceTypeVo);
            }
        }

        //查询无效的设备类型，判断是否正在试用
        //查询当前有效的设备类型
        DeviceTypeQuery deviceTypeQuery_invalid = new DeviceTypeQuery();
        deviceTypeQuery_invalid.setStatus(0); //1-有效；0-禁用
        ArrayList<DeviceType> deviceTypeVos_invalid =  deviceTypeMapper.findByList(deviceTypeQuery_invalid);
        if(deviceTypeVos_invalid != null && deviceTypeVos_invalid.size() > 0){
            for (DeviceType deviceType : deviceTypeVos_invalid){
                if(deviceType.getKey().equals("tiktok")){//需要判断是否给该运营商添加抖音机器人试用权限
                    //从缓存中获取增加抖音试用权限的运营商列表
                    Object object = redisTemplate.opsForValue().get(RedisCacheKeyEnum.DY_DEVICE_AUTH_MERCHAN_LIST.getKey());
                    if(object != null){
                        try {
                            List<Long> merIdList = JSONObject.parseArray(object.toString(), Long.class);
                            //判断是否包含当前运营商，包含则开启该设备类型权限
                            if(merIdList.contains(merId)){
                                //查询当前运营商的设备类型配置
                                MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.DEVICE_SWITCH.getValue());
                                if(merBaseConfig != null){
                                    JSONArray valArray = JSONObject.parseArray(Tools.getStr(merBaseConfig.getVal()));
                                    //是否包含该设备KEY，包含了则设置为1，不包含为0
                                    if(valArray.contains(deviceType.getKey())){
                                        deviceType.setStatus(1);
                                    }else{
                                        deviceType.setStatus(0);
                                    }
                                }else{
                                    deviceType.setStatus(0);
                                }

                                MerchantDeviceTypeVo merchantDeviceTypeVo = new MerchantDeviceTypeVo();
                                BeanUtils.copyProperties(deviceType, merchantDeviceTypeVo);
                                merchantDeviceTypeVos.add(merchantDeviceTypeVo);
                            }
                        }catch (Exception e){

                        }
                    }
                }else if(deviceType.getKey().equals("app")){
                    //从缓存中获取增加抖音试用权限的运营商列表
                    Object object = redisTemplate.opsForValue().get(RedisCacheKeyEnum.APP_DEVICE_AUTH_MERCHAN_LIST.getKey());
                    if(object != null){
                        try {
                            List<Long> merIdList = JSONObject.parseArray(object.toString(), Long.class);
                            //判断是否包含当前运营商，包含则开启该设备类型权限
                            if(merIdList.contains(merId)){
                                //查询当前运营商的设备类型配置
                                MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.DEVICE_SWITCH.getValue());
                                if(merBaseConfig != null){
                                    JSONArray valArray = JSONObject.parseArray(Tools.getStr(merBaseConfig.getVal()));
                                    //是否包含该设备KEY，包含了则设置为1，不包含为0
                                    if(valArray.contains(deviceType.getKey())){
                                        deviceType.setStatus(1);
                                    }else{
                                        deviceType.setStatus(0);
                                    }
                                }else{
                                    deviceType.setStatus(0);
                                }

                                MerchantDeviceTypeVo merchantDeviceTypeVo = new MerchantDeviceTypeVo();
                                BeanUtils.copyProperties(deviceType, merchantDeviceTypeVo);
                                merchantDeviceTypeVos.add(merchantDeviceTypeVo);
                            }
                        }catch (Exception e){

                        }
                    }
                }else if(deviceType.getKey().equals("mini_pro")){
                    //从缓存中获取增加抖音试用权限的运营商列表
                    try {
                        if(Lists.newArrayList("13160220183", "15284924496", "13160220184","13160206693").contains(merchant.getMobile())){
                            //查询当前运营商的设备类型配置
                            MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.DEVICE_SWITCH.getValue());
                            if(merBaseConfig != null){
                                JSONArray valArray = JSONObject.parseArray(Tools.getStr(merBaseConfig.getVal()));
                                //是否包含该设备KEY，包含了则设置为1，不包含为0
                                if(valArray.contains(deviceType.getKey())){
                                    deviceType.setStatus(1);
                                }else{
                                    deviceType.setStatus(0);
                                }
                            }else{
                                deviceType.setStatus(0);
                            }

                            MerchantDeviceTypeVo merchantDeviceTypeVo = new MerchantDeviceTypeVo();
                            BeanUtils.copyProperties(deviceType, merchantDeviceTypeVo);
                            merchantDeviceTypeVos.add(merchantDeviceTypeVo);
                        }
                    }catch (Exception e){

                    }
                }
            }
        }
        return merchantDeviceTypeVos;
    }


    /**
     * 运营商设备启用禁用
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merchantSetDeviceTypeDto
     * @return null
     */
    public Boolean setDeviceType(MerchantSetDeviceTypeDto merchantSetDeviceTypeDto){

        //设置数据库的数据
        Integer currentTime = DateUtil.getNowTime();

        Long merId = merchantSetDeviceTypeDto.getMerId();

        //查询当前运营商的设备类型配置
        MerBaseConfig merBaseConfig_old = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.DEVICE_SWITCH.getValue());

        JSONArray valArray = null;

        if(merBaseConfig_old != null){ //如果存在，则修改
            String val = merBaseConfig_old.getVal();
            if(StringUtils.isNotBlank(val)){
                valArray = JSONObject.parseArray(val);
                //是否包含该设备KEY，包含了则设置为1，不包含为0
                if(merchantSetDeviceTypeDto.getStatus() == 0){ //关闭
                    if(valArray.contains(merchantSetDeviceTypeDto.getKey())){
                        valArray.remove(merchantSetDeviceTypeDto.getKey());
                    }
                }else{ //启动
                    if(!valArray.contains(merchantSetDeviceTypeDto.getKey())){
                        valArray.add(merchantSetDeviceTypeDto.getKey());
                    }
                }
                //修改设备开关配置
                merBaseConfig_old.setVal(JSONObject.toJSONString(valArray));
                merBaseConfig_old.setUpdateTime(currentTime);
                merBaseConfigMapper.update(merBaseConfig_old);
            }
        }else{ //如果没配置，新增配置
            MerBaseConfig merBaseConfig_new = new MerBaseConfig();
            merBaseConfig_new.setId(IdWorker.getId());
            merBaseConfig_new.setMerId(merId);
            merBaseConfig_new.setType(MerConfigTypeEnum.DEVICES.getValue());
            merBaseConfig_new.setKey(MerConfigKeyEnum.DEVICE_SWITCH.getValue());
            valArray = new JSONArray();
            valArray.add(merchantSetDeviceTypeDto.getKey());
            merBaseConfig_new.setVal(JSONObject.toJSONString(valArray));
            merBaseConfig_new.setCreateTime(currentTime);
            merBaseConfig_new.setUpdateTime(currentTime);
            merBaseConfigMapper.insert(merBaseConfig_new);
        }

        //更新redis
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_SWITCH.getKey(), merchantSetDeviceTypeDto.getMerId()), JSONObject.toJSONString(valArray));

        return true;
    }

}
